package com.concurrent.chapter6.concurrent01;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Run {
	public static void main(String[] args) {
		try {
			ExecutorService executorService = Executors.newCachedThreadPool();
			CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
			for (int i = 0; i < 10; i++) {
				completionService.submit(new Callable<String>() {

					@Override
					public String call() throws Exception {
						long sleepValue = (int)(Math.random() * 1000);
						System.out.println("sleep=" + sleepValue + " " + Thread.currentThread().getName());
						Thread.sleep(sleepValue);
						return sleepValue + "-" + Thread.currentThread().getName();
					}
				});
			}
			for (int i = 0; i < 10; i++) {
				//take()方法是按照任务执行的速度，从快到慢获得Future对象
				System.out.println(completionService.take().get());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
